package tq.com.tqteacher.activity.newPublish;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;

import com.browser.DetailPicsActivity;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.donkingliang.imageselector.utils.ImageSelector;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import tq.com.crop.CropIntent;
import tq.com.systools.system.AlertDialogHelper;
import tq.com.systools.system.FileHelper;
import tq.com.systools.system.StringHelper;
import tq.com.tqcom.base.BaseFragment;
import tq.com.tqcom.base.BaseRecyclerFragment;
import tq.com.tqcom.base.BaseTitleActivity;
import tq.com.tqcom.net.INetCallback;
import tq.com.tqcom.net.TQNetClient;
import tq.com.tqcom.net.TQNetResult;
import tq.com.tqcom.net.TQPictureUpload;
import tq.com.tqcom.util.TQEventBus;
import tq.com.tqcom.util.TQLoadingHelper;
import tq.com.tqcom.view.TQHeader5View;
import tq.com.tqteacher.R;
import tq.com.tqteacher.model.TQAtachModel;
import tq.com.tqteacher.model.TQLetShareModel;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.net.TQNetInterface;

public class TQLetShareCaptureActivity extends BaseTitleActivity {
    private TQLetShareCaptureFragment mLetShareCaptureFragment = new TQLetShareCaptureFragment();


    static public void show(Activity pActivity){
        Intent lIntent = new Intent(pActivity, TQLetShareCaptureActivity.class);
        pActivity.startActivity(lIntent);
    }
    @Override
    protected BaseFragment fragment() {
        return mLetShareCaptureFragment;
    }

    @Override
    protected void initHeader(TQHeader5View pHeader5View) {
        super.initHeader(pHeader5View);
        pHeader5View.getTitleView().setText("分享");
    }

    static public class TQLetShareCaptureFragment extends BaseFragment{
        private EditText mTitle;
        private GridView mGridView;

        private ArrayList<Object> pictureData = new ArrayList<>();
        private PictureAadpter mPictureAadpter = new PictureAadpter();

        private int requestCode = 0x12;
        private String mPicCahcePath;
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View lView = inflater.inflate(R.layout.fragment_letsharecapture_layout, container, false);
            mTitle = lView.findViewById(R.id.title);
            mGridView = lView.findViewById(R.id.picture);

            pictureData.add(new Integer(R.drawable.bt_tj));
            mGridView.setAdapter(mPictureAadpter);

            lView.findViewById(R.id.publish).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    share();
                }
            });

            return lView;
        }

        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            mGridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
            mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Object lO = pictureData.get(position);
                    if(lO instanceof Integer){
                        takePhoto();
                    }else{
                        showPicture((String)lO);
                    }
                }
            });
        }

        private void takePhoto(){
            ImageSelector.builder()
                    .setSingle(true)
                    .useCamera(true)
                    .start(this, requestCode);
        }

        private void share(){
            String title = StringHelper.editText(mTitle);
            if(StringHelper.isEmpty(title)){
                AlertDialogHelper.show(getContext(), "标题不能为空");
                return;
            }

            if(pictureData.size() == 1){
                AlertDialogHelper.show(getContext(), "分享内容不能为空");
                return;
            }

            if(!(TQPublishType.getSharePublishItem() instanceof TQLetShareModel)){
                return;
            }

            TQLoadingHelper.build(getContext())
                    .setCancelable(false)
                    .show();

            ArrayList<String> result = new ArrayList<>();
            uploadPicture(0, result);
        }

        private void uploadPicture(final int index, final ArrayList<String> ret){
            if(index >= (pictureData.size() - 1)){
                //bind
                share(ret);
                return;
            }

            TQPictureUpload.uploadPicture((String) pictureData.get(index), new INetCallback() {
                @Override
                public void result(TQNetResult pNetResult) {
                    if(!pNetResult.isSuccess()){
                        TQLoadingHelper.setHelpCancelable(true);
                        TQLoadingHelper.setText(pNetResult.getErrMsg());
                        return;
                    }

                    if(pNetResult.getData() == null) return;
                    String id = pNetResult.getData().optString("fid");
                    ret.add(id);

                    int i = index + 1;
                    uploadPicture(i, ret);
                    TQLoadingHelper.setText(String.format("正在上传%d张", i));
                }
            });
        }
        private void share(final ArrayList<String> result){
            final TQLetShareModel lModel = (TQLetShareModel)TQPublishType.getSharePublishItem();

            final String title = StringHelper.editText(mTitle);
            String files = StringHelper.join(result, ",");

            HashMap<String, String> data = new HashMap<>();
            data.put("filelist", files);
            data.put("desc", title);

            ArrayList<HashMap<String, String>> param = new ArrayList<>();
            param.add(data);

            TQNetInterface.attachFile2Material(TQPublishType.getSharePublishItem().getSeq_id(), param, new INetCallback() {
                @Override
                public void result(TQNetResult pNetResult) {
                    if(!pNetResult.isSuccess()){
                        TQLoadingHelper.setHelpCancelable(true);
                        TQLoadingHelper.setText("分享失败");
                        return;
                    }

                    TQAtachModel lLetShareAttach = new TQAtachModel(title, result);
                    lModel.addAttach(lLetShareAttach);

                    TQEventBus.post(new TQEventBus.TQEventMessage(TQEventBus.TQEventMessage.Opertor.add, lLetShareAttach));
                    TQLoadingHelper.dimiss();
                    TQLetShareCaptureFragment.this.getActivity().finish();
                }
            });
        }

        private void showPicture(String file){
            ArrayList<String> lBrowserPicItems = new ArrayList<>();
            lBrowserPicItems.add(file);

            DetailPicsActivity.jumpToThis(getActivity(), lBrowserPicItems, 0);
        }

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            if(resultCode != Activity.RESULT_OK) return;
            if(requestCode == this.requestCode && data != null){
                ArrayList<String> files = data.getStringArrayListExtra(ImageSelector.SELECT_RESULT);

                if(files != null && files.size() > 0){
                    String file = files.get(0);


                    gotoCrop(file);
//                    pictureData.add(pictureData.size() - 1, file);
//                    mPictureAadpter.notifyDataSetChanged();
                }
            }else if(requestCode == 0x13){
                if(!StringHelper.isEmpty(mPicCahcePath)){
                    pictureData.add(pictureData.size() - 1, mPicCahcePath);
                    mPictureAadpter.notifyDataSetChanged();
                }

            }
            super.onActivityResult(requestCode, resultCode, data);
        }

        private void close(Object pO){
            pictureData.remove(pO);
            mPictureAadpter.notifyDataSetChanged();
        }

        private void gotoCrop(String file){
            mPicCahcePath = FileHelper.picCacheFile();

            CropIntent intent = new CropIntent();
            intent.setImagePath(file);
            intent.setRotate(false);
            intent.setOutputPath(mPicCahcePath);
            startActivityForResult(intent.getIntent(this.getContext()), 0x13);
        }

        class PictureAadpter extends BaseAdapter{
            @Override
            public Object getItem(int position) {
                return pictureData.get(position);
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                Object lO = pictureData.get(position);
                View lView = convertView;
                if(lView == null){
                    lView = LayoutInflater.from(getContext()).inflate(R.layout.vh_letshare_cpicture, parent, false);
                }

                ImageView close = lView.findViewById(R.id.close);
                ImageView pic = lView.findViewById(R.id.picture);
                close.setTag(lO);

                if(lO instanceof String){
                    close.setVisibility(View.VISIBLE);
                    Glide.with(getContext()).load(new File((String) lO)).into(pic);
                }else{
                    close.setVisibility(View.INVISIBLE);
                    int res = (Integer) lO;
                    RequestOptions lOptions = new RequestOptions().placeholder(res);
                    Glide.with(getContext()).load("").apply(lOptions).into(pic);
                }

                close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        close(v.getTag());
                    }
                });
                return lView;
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public int getCount() {
                return pictureData.size() > 4 ? 4 : pictureData.size();
            }
        }
    }


}
